import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        // websocket相关对象
        ws: {},
        wsurl: '',
        msg: '未连接',//消息
        wsst: 0, //ws状态0为未连接,1为已连接为认证,2为已连接且已认证
        token: '', //认证所需要的令牌
        // 用户相关对象
        ulist: [
            {
                uid: 1,
                name: 'lyp',
                petname: '刘云鹏',
                memo: '这是签名',
                icon: 'xxxpng',
                gid: 1,
                msg: [
                    {
                        form: '1',//发送人id
                        to: '1',//接收人id
                        msg: '消息内容',//消息内容
                        time: 1234123,//消息时间戳
                        state:true//读取状态

                    }
                ]
            }
        ]
    },
    mutations: {
        setulist(state, data) {
            state.ulist = data
        },
        settoken(state, token) {
            state.token = token
        },
        setwsurl(state, url) {
            state.wsurl = url
        },
        setwsst(state, wsst) {
            state.wsst = wsst
        },
        setmsg(state, msg) {
            state.msg = msg
        },
        setws(state, ws) {
            state.ws = ws
        },
        linkws(state) {
            state.ws = new WebSocket(state.wsurl)
        }
    },
    actions: {
        wsopen(store) {
            let ws = store.state.ws

            ws.onopen = function () {
                store.commit('setwsst', 1)
                store.commit('setmsg', '已经连接上')
                let msg = {
                    type: 'auth',
                    token: store.state.token
                }// 创建认证请求
                let data = JSON.stringify(msg) // 将请求转换为json字符串
                ws.send(data)
            }, ws.onclose = function () {
                store.commit('setwsst', 0)
                store.commit('setmsg', '连接已断开')
            }
            /*消息处理*/
            ws.onmessage = function (msg) {
                let sdata = msg.data
                let data = JSON.parse(msg.data)
                store.commit('setmsg', msg.data)

                switch (data.type) {
                    case 'reauth':
                        if (data.result === 1) {
                            store.commit('setwsst', 2) // 连接上且已经认证

                            ws.send('{"type":"qulist"}')

                        } else {
                            store.commit('setwsst', 1)
                        }
                        break
                    case 'relist':
                        let ulist = data.result
                        store.commit('setulist', ulist)
                        break
                    case 'message':
                        ws.send('{"type":"qulist"}')
                        break

                }
            }
            store.commit('setws', ws)// 提交实例修改
        }
    }
})